<?php
namespace app\common\model\video;

use app\common\model\BaseModel;

/**课程模型
 * Class Course
 * @package app\common\model
 */
class Course extends BaseModel
{
    protected $pk = 'id';
    protected $name = 'video';

    public function getStatusAttr($value): array
    {
        $data = [
            1 => ['text' => '上架', "value" => 1],
            2 => ['text' => '下架', 'value' => 2]
        ];
        return $data[$value];
    }

    public function cate(): \think\model\relation\BelongsTo
    {
        return $this->belongsTo(CourseCate::class, 'cate_id', 'id')->field('id,name');
    }

    /**关联章节模型
     * @return \think\model\relation\HasMany
     */
    public function part()
    {
        return $this->hasMany(CoursePart::class, 'c_id', 'id');
    }

    public function getContentAttr($value)
    {
        return htmlspecialchars_decode($value);
    }

    /**
     * 关联文件库
     * @return \think\model\relation\BelongsTo
     */
    public function image()
    {
        $module = self::getCalledModule()?:"common";
        return $this->belongsTo("app\\{$module}\\model\\UploadFile", 'cover_image', 'file_id')
            ->bind(['file_path', 'file_name', 'file_url']);
    }

    public function getList($where = [], $with = ['cate'], $limit = 15)
    {
        $params = array_merge([
            'cate_id' => 0,         // 商品状态
            'status' => '',         // 商品状态
            'name' => '',         // 搜索关键词
        ], $where);
        // 筛选条件
        $filter = [];
        $params['status'] != '' && $filter['status'] = $params['status'];
        $params['cate_id'] > 0 && $filter['cate_id'] = $params['cate_id'];
        !empty($params['name']) && $filter['name'] = ['like', '%' . trim($params['name']) . '%'];
        return $this->where('is_delete', 0)
            ->with($with)->withCount(['part'],false)
            ->where($filter)
            ->field('id,name,cate_id,price,line_price,status,sort,cover_image,describe,create_time,validate_type,days,sales_initial,sales_actual')
            ->order(['sort' => 'asc'])
            ->paginate($limit);
    }

    public function getAllList(){
        return $this->where(['is_delete'=>0])->field('id,name')->select();
    }

    // 添加
    public function add($params)
    {
        $params['wxapp_id'] = self::$wxapp_id;
        return $this->insert($params) != false;
    }

    public static function detail($id){
        return (new static())::get($id,['image','part','part.image']);
    }
}
